import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client implements Runnable {
    private Socket socket;
    private NetWork network;
    private PrintStream out;
    private boolean isCloseSocket = false;
    String name = "";
    public Client(Socket socket, NetWork network) {
        this.network = network;
        this.socket = socket;
    }


    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                out = new PrintStream(socket.getOutputStream(), true);
                Scanner in = new Scanner(socket.getInputStream());

                sendMessage("Hello, whats is your name?");
                String input;
                while (!isCloseSocket) {
                    input = in.nextLine();

                    if (input.equals("bye")) {
                        sendMessage("Good Bye");
                        network.removeClients(this);
                        isCloseSocket = true;
                        Thread.currentThread().interrupt();

                        break;
                    }

                    if (!name.isEmpty()) {
                        network.sendMessageForChat(name + ": " + input, name);

                    }

                    if (name.isEmpty()) {
                        name = input;
                        network.addClients(this);
                        sendMessage("Hello, " + name + "!!!");
                        sendMessage("I,am glade too see yuo!)");
                    }

                }
                System.out.println(name + " left");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    void sendMessage(String message) {
        out.println(message);
    }
}
